using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2013.TimerJob;
using ServBus.ListForm2013.Resources;
using ServBus.ListForm2013.Utility;
using ServBus.ListForm2013.License;

namespace ServBus.ListForm2013.Feature
{
    public class AdminFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            SPWebApplication webapp = web.Site.WebApplication;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                if (webapp == null)
                    throw new ArgumentNullException();
                if (webapp.IsAdministrationWebApplication)
                {
                    try
                    {
                        SyncActivationJob.InstallToWebapp(webapp);
                    }
                    catch (SPDuplicateObjectException)
                    {
                    }
                    
                    // Modify Web Config
                    ResourceUtility.InstallToWebConfig(webapp);
                }
            });
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            // Remove Admin Jobs
            foreach (SPWebApplication adminWebapp in SPWebService.AdministrationService.WebApplications)
            {
                SyncActivationJob.RemoveFromWebapp(adminWebapp);
                // Remove Web Config
                ResourceUtility.RemoveFromWebConfig(adminWebapp);
            }

            // Remove Global Properties
            UninstallProperties();
        }

        private void UninstallProperties()
        {
            // Remove from each webapp
            foreach (SPWebApplication webapp in SPWebService.ContentService.WebApplications)
            {
                Activations.DeactivateWebApp(webapp);
            }

            // Remove from farm
            SPFarm farm = SPFarm.Local;
            if (farm.Properties.ContainsKey(Constants.ACTIVATION_PROPERTY_KEY))
                farm.Properties.Remove(Constants.ACTIVATION_PROPERTY_KEY);
            if (farm.Properties.ContainsKey(Constants.FARM_LICENSE_KEY))
                farm.Properties.Remove(Constants.FARM_LICENSE_KEY);
            farm.Update();
        }
    }
}
